﻿using System.Windows;
using System.IO;
using System.Reflection;

namespace Com.CodePlex.SPC3.SPbAM.View {

	public partial class MainWindowView : Window {

		public ViewModel.MainWindowViewModel ViewModel {
			get { return (ViewModel.MainWindowViewModel)DataContext; }
		}

		public MainWindowView() {
			InitializeComponent();
			RecentFileList.UseXmlPersister(Path.Combine(Directory.GetCurrentDirectory(), "recentfiles.xml"));
			RecentFileList.MenuClick += (s, e) => {
				ViewModel.Open(e.Filepath);
			};
			Loaded += (s, e) => {
				if (RecentFileList.RecentFiles.Count > 0) {
					ViewModel.Open(RecentFileList.RecentFiles[0]);
				}
			};
			DataContextChanged += (s, e) => {
				ViewModel.Opening += (s1, e1) => {
					RecentFileList.InsertFile(((SimpleEventArgs)e1).StringValue);
				};
				ViewModel.RequestClose += (s1, e1) => {
					bool cancel = false;
					if (ViewModel.WarnClose()) {
						MessageBoxResult result = MessageBox.Show("Close without saving?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Question);
						if (result == MessageBoxResult.No) {
							cancel = true;
						}
					}
					if (!cancel) {
						ViewModel.Close();
					}
				};
				ViewModel.RequestExit += (s1, e1) => {
					Close();
				};
			};
			Closing += (s, e) => {
				if (ViewModel.WarnExit()) {
					MessageBoxResult result = MessageBox.Show("Exit without saving?", "Warning", MessageBoxButton.YesNo, MessageBoxImage.Question);
					if (result == MessageBoxResult.No) {
						e.Cancel = true;
					}
				}
				if(!e.Cancel) {
					ViewModel.Exit();
				}
			};
		}
	}
}
